#include <QLayout>
#include <QDir>
#include "openfiledialog.h"

std::string OpenFileDialog::s_strFolder = "";
std::string OpenFileDialog::s_strFilename = "";

OpenFileDialog::OpenFileDialog(QWidget *parent)
: QDialog(parent)
{
    this->setWindowTitle("Choose Files");
    createWidgets();
    createConnections();
    slotFolderChanged();
}

void OpenFileDialog::createWidgets()
{
    QHBoxLayout* hboxFolder = new QHBoxLayout();
    QHBoxLayout* hboxFilename = new QHBoxLayout();
    QHBoxLayout* hboxBtn = new QHBoxLayout();

    QDir dir;
    dir.setPath("data");
    QStringList strList = dir.entryList(QDir::AllDirs | QDir::NoDot | QDir::NoDotDot);
    m_comboFolder = new QComboBox(this);
    m_comboFolder->addItems(strList);
    m_FolderLabel = new QLabel("File Folder");
    hboxFolder->addWidget(m_FolderLabel);
    hboxFolder->addWidget(m_comboFolder);

    m_FilenameLabel = new QLabel("File Name");
    m_fileEdit = new QLineEdit();
    hboxFilename->addWidget(m_FilenameLabel);
    hboxFilename->addWidget(m_fileEdit);

    m_btnOK = new QPushButton("OK");
    m_btnCancel = new QPushButton("Cancel");
    hboxBtn->addWidget(m_btnOK);
    hboxBtn->addWidget(m_btnCancel);

    QVBoxLayout* mainLayout = new QVBoxLayout();
    mainLayout->setMargin(4);
    mainLayout->addLayout(hboxFolder);
    mainLayout->addLayout(hboxFilename);
    mainLayout->addLayout(hboxBtn);
    setLayout(mainLayout);
}

void OpenFileDialog::createConnections()
{
    connect(m_btnOK, SIGNAL(clicked()), this, SLOT(accept()));
    connect(m_btnCancel, SIGNAL(clicked()), this, SLOT(reject()));
    connect(m_comboFolder, SIGNAL(currentIndexChanged(int)), this, SLOT(slotFolderChanged()));
}

void OpenFileDialog::slotFolderChanged()
{
    char filename[100];
    std::string str = m_comboFolder->currentText().toStdString();
    QString strPath = "data";
    strPath += "\\";
    strPath += str.c_str();
    QDir dir;
    dir.setPath(strPath);
    QStringList strList = dir.entryList(QDir::Files);
    for (int i = 0; i < strList.size(); ++i) {
        strcpy(filename, strList[i].toLatin1().data());
        char *endPos = strstr(filename, "43200");
        if (!endPos)
            continue;
        *endPos = '\0';
        m_fileEdit->setText(filename);
        continue;
    }
}

void OpenFileDialog::accept()
{
    s_strFolder = m_comboFolder->currentText().toStdString();
    s_strFilename = m_fileEdit->text().toStdString();
    QDialog::accept();
}